package com.example.interceptor;

import com.example.enums.BizCodeEnum;
import com.example.model.LoginUser;
import com.example.utils.CommonUtil;
import com.example.utils.JWTUtil;
import com.example.utils.JsonData;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yinxin
 * @version 1.0
 * @Description:
 * @date 2022/6/713:06
 */
public class LoginInterceptor implements HandlerInterceptor {

    //一个贯穿整个应用的主线程
    public static ThreadLocal<LoginUser> threadLocal= new ThreadLocal<LoginUser>();

    //预处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())){
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }
        String accessToken = request.getHeader("token");
        if(StringUtils.isBlank(accessToken)){
            accessToken =request.getParameter("token");
        }
        if(StringUtils.isNotBlank(accessToken)){
            Claims claims = JWTUtil.checkJWT(accessToken);
            if(claims==null){
                //未登录
                CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
                return false;
            }
            Long accountNo = Long.parseLong(claims.get("account_no").toString());
            String headImg = claims.get("head_img").toString();
            String username = claims.get("username").toString();
            String mail = claims.get("mail").toString();
            String phone = claims.get("phone").toString();
            String auth = claims.get("auth").toString();

            LoginUser loginUser = LoginUser.builder()
                    .accountNo(accountNo)
                    .auth(auth).headImg(headImg)
                    .username(username)
                    .mail(mail)
                    .phone(phone)
                    .build();
            request.setAttribute("loginUser",loginUser);

            //通过threadloacl
            threadLocal.set(loginUser);

            return true;

        }
        return false;
    }

    //后处理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //返回处理
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }
}
